<template>
  <div class="view-fill">
    <div
      v-if="
        !purchOrderCheckApplicationInfo.visible &&
        !detailInfo.visible &&
        !modifyInfo.visible
      "
      class="app-container-flex"
    >
      <NewFullScreen
        v-model="showDialog"
        title="申购汇总单明细"
        @returnBack="returnBack"
        :btnList="fullInfo.btnList"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
      >
        <template v-slot:full-button>
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="canPrint"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <!-- <el-button v-if="canPrint" @click="print">打印</el-button> -->
          <el-button v-if="canExcel" @click="exportExcel">导出excel</el-button>
          <el-button v-if="canSubmit" @click="submit">提交</el-button>
          <el-button v-if="revoke" @click="revokeOrder">撤回</el-button>
          <el-button v-if="ratify" @click="audit">批准</el-button>
          <el-button v-if="canReject" @click="reject">驳回</el-button>
          <el-button v-if="stop" @click="checkBreak">中止</el-button>
          <el-button
            v-if="
              (proxy.$permission('applicationSummary:createPurchOrder') &&
                infoList.data.status === 5) ||
              infoList.data.status === 3
            "
            @click="generatePurchOrder"
            >生成采购单</el-button
          >
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="infoList"> </basic-information>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <p>申购单列表</p>
          </div>
          <div class="model-panel-body">
            <new-page-filter :filter-btn="filterOrderInfo.btnList">
              <template v-slot:filter-add>
                <el-button :disabled="infoList.data.status !== 1" @click="add"
                  >添加申购单</el-button
                >
              </template>

              <template v-slot:filter-delete>
                <el-button :disabled="canRemove" @click="remove"
                  >删除</el-button
                >
              </template>
            </new-page-filter>
            <div class="flex_full_item">
              <page-table
                :pager="false"
                :field-list="orderInfo.fieldList"
                :handle="orderInfo.handle"
                v-model:data="orderInfo.data"
                @handleEvent="handleOrderEvent"
              >
                <template v-slot:col-orderNo="scope">
                  <span class="slip-edit" @click="showDetail(scope.row)">{{
                    scope.row.orderNo
                  }}</span>
                </template>
              </page-table>
            </div>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')"></Tooltip>
            <div class="model-tips">
              (证照：<span>近效期</span>
              <span class="model-tips-nearly"></span>
            </div>
            <div class="model-tips">
              <span>过期</span>
              <span class="model-tips-expire"></span>)
            </div>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :checkBox="true"
                :summary="true"
                :defaultSort="tableInfo.defaultSort"
                :api="tableInfo.api"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :summary-field-list="tableInfo.summaryFieldList"
                :row-class-name="tableRowClassName"
              >
              </page-table>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <purch-application-modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :orderId="modifyInfo.purchApplicationId"
      :is-special-edit="modifyInfo.isSpecialEdit"
      @returnModify="returnModify"
    />
    <purch-application-details
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :tableRow="detailInfo.data"
    ></purch-application-details>
    <select-order
      v-if="showSelectOrder"
      v-model:show-dialog="showSelectOrder"
      :query="showSelectOrderQuery"
      @callback="callbackOrder"
    ></select-order>
    <purch-order-check-application
      v-if="purchOrderCheckApplicationInfo.visible"
      v-model:visible="purchOrderCheckApplicationInfo.visible"
      :purchApplicationId="purchOrderCheckApplicationInfo.orderId"
      :purch-application-info="purchOrderCheckApplicationInfo.info"
      :purch-type="purchOrderCheckApplicationInfo.purchType"
      :purch-according="purchOrderCheckApplicationInfo.purchAccording"
      :title="purchOrderCheckApplicationInfo.title"
      @returnModify="returnModify"
    />
    <page-dialog
      v-if="pageDialogInfo.visible"
      :title="pageDialogInfo.title"
      v-model:visible="pageDialogInfo.visible"
      :width="pageDialogInfo.width"
      :bt-loading="pageDialogInfo.btLoading"
      :bt-list="pageDialogInfo.btList"
      @reset="closeDialog"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="pageFormInfo.ref"
        :data="pageFormInfo.data"
        :field-list="pageFormInfo.fieldList"
        :label-width="pageFormInfo.labelWidth"
      />
    </page-dialog>
  </div>
</template>

<script setup name="applicationSummaryDetail">
import {
  getApplicationSummaryOrderById,
  applicationSummaryDeletePurchOrder,
  applicationSummaryAddPurchOrder,
  applicationSummaryDetailCustomizeListAll,
  applicationSummaryBatchReject,
  getPurchApplicationAll,
  exportApplicationSummary,
  getPurchApplicationSummaryPrint,
} from '@/api/purch.js'
import { getReceiveAddressAll, getCoreSystemConfigAll } from '@/api/core'
import { getCustomizeSetting } from '@/api/customize'
// import BasicInformation from "@/components/BasicInformation/index";
import { orderAffairAll } from '@/api/affair'
import PurchOrderCheckApplication from '@/views/purch/order/checkPurchApplication.vue'
import PurchApplicationDetails from '@/views/purch/application/detail'
import PurchApplicationModify from '@/views/purch/application/modify'
import SelectOrder from './selectOrder'
import { fatchTemplateByCode } from '@/api/base'
import {
  applicationSummaryOrderSubmit,
  applicationSummaryOrderRevoke,
  applicationSummaryOrderReject,
  applicationSummaryOrderRatifyt,
  applicationSummaryStop,
} from '@/api/purch.js'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'

const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps({
  visible: {
    type: Boolean,
  },
  tableRow: {
    type: Object,
    default: function () {
      return {}
    },
  },
})

const infoList = reactive({
  data: {},
  fieldList: [
    { label: '申购汇总单号', value: 'orderNo', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '创建人', value: 'createUserName', type: 'text' },
    { label: '创建时间', value: 'createTime', type: 'text' },
    { label: '审批人', value: 'updateUserName', type: 'text' },
    { label: '审批时间', value: 'updateTime', type: 'text' },
    { label: '是否临采', value: 'temporaryPurchValue', type: 'text' },
  ],
})

// 过滤相关配置
const filterInfo = reactive({
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.tableRow.id,
      },
    },
    customizeUserVO: {},
  },
})

const fullInfo = reactive({
  btnList: [],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  fieldList: [],
  summaryFieldList: [
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
})
const affairTableInfo = reactive({
  api: orderAffairAll,
  query: {
    orderType: 31,
    orderId: props.tableRow.id,
    sort: 'operate_time desc',
  },
})
const systemConfig = ref({})
const filterOrderInfo = reactive({
  btnList: [
    {
      value: 'add',
      type: 'slot',
      show: proxy.$permission('applicationSummary:add'),
    },
    {
      value: 'delete',
      type: 'slot',
      show: proxy.$permission('applicationSummary:delete'),
    },
  ],
})
const orderInfo = reactive({
  data: [],
  selections: [],
  fieldList: [
    { label: '申购单号', value: 'orderNo', type: 'slot' },
    { label: '部门', value: 'deptName' },
    { label: '创建人', value: 'createUserName' },
    { label: '更新时间', value: 'updateTime' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        type: 'button',
        label: '驳回',
        event: rejectBatch,
        show: proxy.$permission('applicationSummary:reject'),
        ifRender: (row) => {
          return row.status === 9 && infoList.data.status === 2
        },
      },
      {
        type: 'button',
        label: '特殊修改',
        event: update,
        show: proxy.$permission('applicationSummary:specialUpdate'),
        ifRender: (row) => {
          return row.status === 12 && infoList.data.status === 1
        },
      },
    ],
  },
})
const detailInfo = reactive({
  visible: false,
  data: {},
})
const modifyInfo = reactive({
  visible: false,
  title: '',
  purchApplicationId: '',
  isSpecialEdit: 1,
})
const purchOrderCheckApplicationInfo = reactive({
  visible: false,
  title: '通过申购汇总单生成采购单',
  orderId: null,
  purchType: 1,
  info: undefined,
})
const pageDialogInfo = reactive({
  title: '选择采购依据',
  visible: false,
  type: '',
  width: '400px',
  row: {},
  btLoading: false,
  btList: [
    {
      label: '关闭',
      type: '',
      icon: '',
      event: closeDialog,
      show: true,
    },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: saveDialog,
      saveLoading: false,
      show: true,
    },
  ],
})
const pageFormInfo = reactive({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '采购依据',
      value: 'purch_according',
      type: 'select-model',
      code: 'purch_according',
    },
  ],
})
const showSelectOrder = ref(false)
const showSelectOrderQuery = ref({})

let obj = reactive({
  price: {
    label: '单价',
    value: 'price',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('applicationSummary:price'),
    hidden: true,
  },
  orderNo: {
    label: '单号',
    value: 'orderNo',
    componentType: 'input',
    show: false,
    type: 'column',
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('applicationSummary:price'),
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('applicationSummary:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
  userDefaultDepotStockQty: {
    label: '用户默认仓库库存量',
    value: 'userDefaultDepotStockQty',
    type: 'column',
    show: false,
    hidden: true,
  },
})
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canPrint = computed(() => {
  return (
    proxy.$permission('applicationSummary:print') && infoList.data.status !== 1
  )
})
const canExcel = computed(() => {
  return (
    proxy.$permission('applicationSummary:excel') && infoList.data.status !== 1
  )
})
const canRemove = computed(() => {
  if (orderInfo.selections.length) {
    if (infoList.data.status === 1) {
      return false
    } else {
      return true
    }
  } else {
    return true
  }
})
//提交
const canSubmit = computed(() => {
  return (
    proxy.$permission('applicationSummary:submit') && infoList.data.status === 1
  )
})
//撤回
const revoke = computed(() => {
  let type = false
  if (infoList.data.status === 2) {
    type = true
  } else if (infoList.data.status === 3) {
    if (infoList.data.beforeMergeStatus === 3) {
      type = true
    } else {
      type = false
    }
  }
  return proxy.$permission('applicationSummary:revoke') && type
})
//批准
const ratify = computed(() => {
  return (
    proxy.$permission('applicationSummary:audit') && infoList.data.status === 2
  )
})
//驳回
const canReject = computed(() => {
  return (
    proxy.$permission('applicationSummary:reject') && infoList.data.status === 2
  )
})
//停止
const stop = computed(() => {
  let type = false
  if (infoList.data.status === 5) {
    type = true
  } else if (infoList.data.status === 3) {
    if (infoList.data.beforeMergeStatus === 2) {
      type = true
    } else {
      type = false
    }
  }
  return proxy.$permission('applicationSummary:stop') && type
})
watch(
  () => props.visible,
  (value) => {
    showDialog.value = value
  },
  {
    immediate: true,
  }
)
watch(
  () => props.tableRow,
  (newVal) => {
    filterInfo.query.queryMap.orderId.value = newVal.id
    affairTableInfo.query.orderId = newVal.id
    getCustomize()
  },
  {
    immediate: true,
    deep: true,
  }
)

function returnModify() {
  if (infoList.data.id) {
    getCustomize()
  }
}
//提交
function submit() {
  applicationSummaryOrderSubmit([infoList.data.id]).then((res) => {
    if (res && res.success) {
      getCustomize()
    }
  })
}
//终止
function checkBreak() {
  applicationSummaryStop([infoList.data.id]).then((res) => {
    if (res && res.success) {
      getCustomize()
    }
  })
}
function revokeOrder() {
  applicationSummaryOrderRevoke([infoList.data.id]).then((res) => {
    if (res && res.success) {
      getCustomize()
    }
  })
}
//驳回
function reject() {
  proxy
    .$prompt('请输入驳回理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
    .then(({ value }) => {
      const data = {
        id: infoList.data.id,
        rejectReason: value,
      }
      applicationSummaryOrderReject(data).then((resp) => {
        if (resp && resp.success) {
          getCustomize()
        }
      })
    })
}
function audit() {
  //批准
  applicationSummaryOrderRatifyt([infoList.data.id]).then((res) => {
    if (res && res.success) {
      getCustomize()
    }
  })
}

function ifRenderPrint() {
  const status = infoList.data.status
  return status !== 1
}
function callbackOrder(ids) {
  let params = {
    version: infoList.data.version,
    id: infoList.data.id,
    mergeApplicationIds: ids,
  }
  applicationSummaryAddPurchOrder(params).then((res) => {
    if (res && res.success) {
      getList()
      getMain()
      getApplictionOrderList()
      getValueList()
    }
  })
}
function returnBack() {
  emits('returnBack', false)
}
function getList() {
  tableInfo.refresh = Math.random()
}

function getMain() {
  getApplicationSummaryOrderById(props.tableRow.id).then((resp) => {
    if (resp && resp.success) {
      infoList.data = resp.data
    }
  })
}
function getApplictionOrderList() {
  getPurchApplicationAll({ summaryId: props.tableRow.id }).then((resp) => {
    if (resp && resp.success) {
      orderInfo.data = resp.data
    }
  })
}
//导出excel
function exportExcel() {
  exportApplicationSummary(filterInfo.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  console.log(infoList.data)
  selectByCodeAndDept({
    tempCode: 'purchApplicationSummaryDetail',
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            orderId: props.tableRow.id,
            orderNo: props.tableRow.orderNo,
          },
          callback: printCallback,
          printCount: true,
          data: {},
        })
      }
    }
  })
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.data.orderNo,
      orderId: infoList.data.id,
      orderType: 31,
    })
  } catch (error) {}
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      orderId: props.tableRow.id,
      orderNo: props.tableRow.orderNo,
    },
    callback: printCallback,
    printCount: true,
    data: {},
  })
  popoverVisible.value = false
}
function getPirntData(temp) {
  let params = {
    tableKey:
      'purchApplicationSummaryDetail-com.slip.spd.entity.vo.purch.PurchApplicationSummaryDetailVO',
    orderIds: [props.tableRow.id],
  }
  getPurchApplicationSummaryPrint(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(
        temp,
        newData,
        !proxy.$permission('applicationSummary:price')
      )
    }
  })
}
function closeDialog() {
  pageDialogInfo.visible = false
  pageFormInfo.data = {}
}
//生成采购单
function generatePurchOrder() {
  if (
    proxy.$store.state.permission.systemConfig.purch_according != '1' &&
    proxy.$store.state.permission.systemConfig.purch_according != '2'
  ) {
    pageDialogInfo.visible = true
  } else {
    const params = {
      isDefault: '1',
    }
    getReceiveAddressAll(params).then((resp) => {
      if (resp && resp.success) {
        purchOrderCheckApplicationInfo.visible = true
        purchOrderCheckApplicationInfo.orderId = infoList.data.id
        purchOrderCheckApplicationInfo.info = infoList.data
        purchOrderCheckApplicationInfo.purchAccording =
          proxy.$store.state.permission.systemConfig.purch_according
      }
    })
  }
}
function saveDialog() {
  if (pageFormInfo.data.purch_according) {
    const params = {
      isDefault: '1',
    }
    getReceiveAddressAll(params).then((resp) => {
      if (resp && resp.success) {
        purchOrderCheckApplicationInfo.orderId = infoList.data.id
        purchOrderCheckApplicationInfo.info = infoList.data
        purchOrderCheckApplicationInfo.purchAccording =
          pageFormInfo.data.purch_according
        closeDialog()
        proxy.$nextTick(() => {
          purchOrderCheckApplicationInfo.visible = true
        })
      }
    })
    return
  } else {
    proxy.$message.warning('请选择采购依据')
  }
}
function getValueList() {
  getCoreSystemConfigAll().then((resp) => {
    if (resp && resp.success) {
      const data = {}
      resp.data.forEach((item) => {
        data[item.systemConfigCode] = item.value
      })
      systemConfig.value = data
    }
  })
}
function tableRowClassName({ row = undefined }) {
  if (row.licenseEndDate) {
    let dataDiff = proxy.$fn.dateDiff(new Date(), row.licenseEndDate)
    if (dataDiff <= 0) {
      return 'expire-row'
    } else if (
      Number(systemConfig.value.license_nearly_effective) >=
      dataDiff >
      0
    ) {
      return 'nearly-row'
    }
  }
  return ''
}
//新增
function add() {
  showSelectOrder.value = true
  let ids = orderInfo.data.map((a) => a.id)
  showSelectOrderQuery.value = {
    idNotIn: ids.toString(),
    temporaryPurch: infoList.data.temporaryPurch,
    status: orderInfo.data[0].beforeMergeStatus,
  }
}
//删除
function remove() {
  if (orderInfo.selections.length) {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        let ids = orderInfo.selections.map((a) => a.id)
        let params = {
          version: infoList.data.version,
          id: infoList.data.id,
          mergeApplicationIds: ids,
        }
        applicationSummaryDeletePurchOrder(params).then((res) => {
          if (res && res.success) {
            getList()
            getMain()
            getApplictionOrderList()
            getValueList()
          }
        })
      })
  }
}
function rejectBatch(row) {
  proxy
    .$prompt('请输入驳回理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
    .then(({ value }) => {
      const data = {
        id: infoList.data.id,
        rejectApplicationIds: Array.of(row.id),
        rejectReason: value,
      }
      applicationSummaryBatchReject(data).then((res) => {
        if (res && res.success) {
          getMain()
          getApplictionOrderList()
          getList()
          getValueList()
        }
      })
    })
}
function handleOrderEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      orderInfo.selections = [...data]
      break
  }
}
function showDetail(row) {
  detailInfo.visible = true
  detailInfo.data = { ...row }
}
function update(row) {
  modifyInfo.visible = true
  modifyInfo.title = '修改申购单'
  modifyInfo.updateType = 0
  modifyInfo.purchApplicationId = row.id
}
function getCustomize() {
  let param = {
    tableKey:
      'purchApplicationSummaryDetail-com.slip.spd.entity.vo.purch.PurchApplicationSummaryDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(tableInfo.fieldList, data.detail, true)
      tableInfo.fieldList = obj.fieldList
      tableInfo.api = applicationSummaryDetailCustomizeListAll
      getValueList()
      getMain()
      getApplictionOrderList()
      getList()
    }
  })
}
</script>

<style scoped lang="scss">
.model-panel-title {
  display: flex;
  align-items: center;
  .model-tips {
    display: flex;
    align-items: center;
    margin-left: 10px;
    color: #909399;
    .model-tips-nearly,
    .model-tips-expire {
      display: block;
      margin-left: 5px;
      width: 17px;
      height: 17px;
    }
    .model-tips-nearly {
      background: #fceacb;
    }
    .model-tips-expire {
      background: #f5e4e4;
    }
  }
}
// :deep(.el-table) .nearly-row {
//   background: #fceacb;
// }
// :deep(.el-table) .expire-row {
//   background: #f5e4e4;
// }
// :deep(.el-table__body) tr.hover-row > td {
//   background-color: transparent !important;
// }
// :deep(.caret-wrapper) {
//   display: none;
// }
</style>
